package com.ncloud.workflow.service.impl;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.workflow.service.ProcessInstanceService;

@Service
public class ProcessInstanceServiceImpl implements ProcessInstanceService {

	@Autowired
	private RuntimeService runtimeService;
	
	@Override
	public Object startProcessInstance(JSONObject json) {
		String key = json.getString("key");
		String businessKey = json.getString("businessKey");
		JSONObject variables = json.getJSONObject("variables");
		if(StringUtils.isNoneBlank(key)){
			ProcessInstance pi = runtimeService.startProcessInstanceByKey(key, businessKey, variables);
			return pi.getProcessInstanceId();
		}
		return HttpStatus.BAD_REQUEST;
	}

	@Override
	public Object suspendProcessInstance(JSONObject json) {
		if(json.containsKey("processInstanceId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		String pId = json.getString("processInstanceId");
		runtimeService.suspendProcessInstanceById(pId);
		return HttpStatus.OK;
	}

	@Override
	public Object activeProcessInstance(JSONObject json) {
		if(json.containsKey("processInstanceId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		String pId = json.getString("processInstanceId");
		runtimeService.activateProcessInstanceById(pId);
		return HttpStatus.OK;
	}
	
}
